import { ResultUtil } from '../common/HandlerRespUtil';
import { Config } from '../sdk/ConfigManager';
import { LingmaSDKTool } from '../sdk/LingmaSDKTool';
import axios from 'axios';
import moment from 'moment';
import os from 'os';
import {
  AIResponse,
  HandlePolicy,
  RawRequest,
  RequestPostHandler,
} from '../sdk/RequestHandleSDK';

/**
 * Custom script filter, through which request content can be sent to a remote server for processing (such as code scanning, content audit, etc.)
 */
export const llmCompletionResultAuditHandler: RequestPostHandler = {
  handle: async (request: RawRequest, response: AIResponse, SDKTool: LingmaSDKTool) => {
    // Operator name
    const userName = SDKTool.user.name;
    // Operator ID
    const userId = SDKTool.user.uid;
    // IDE
    const ide = SDKTool.idePlatform;
    // IDE version
    const { ideVersion } = SDKTool;
    // Operation time
    const operationTime = moment().format('YYYY-MM-DD HH:mm:ss');
    // Operation IP
    const opeartionIp = getIpAddress();
    // Operation business scenario (completion or Q&A scenario)
    const bizType = 'completion';
    // Operation request ID
    const { requestId } = request;
    // Operation action
    const { action } = request;
    // Operation content (it is recommended to select appropriate fields based on audit requirements to avoid reporting too much content (over 16k) leading to reporting failure)
    const inferredResult = response.inferredResult.text;

    // Report to SLS
    // SLS Project name
    const slsProject = 'xxx';
    // SLS LogStore name
    const slsLogStore = 'xxx';
    // SLS instance region endPoint
    const endPoint = 'cn-hangzhou.log.aliyuncs.com';
    const slsWebTrackingUrl = `http://${slsProject}.${endPoint}/logstores/${slsLogStore}/track?APIVersion=0.6.0&request_id=${requestId}&action=${action}&biz_type=${bizType}&user_name=${userName}&user_id=${userId}&ide=${ide}&ide_version=${ideVersion}&operation_time=${operationTime}&opeartion_ip=${opeartionIp}&inferredResult=${inferredResult}`;
    axios.get(slsWebTrackingUrl).catch((error) => {
      console.error(error);
    });

    // Return filter result
    return ResultUtil.buildPostHandlerResponse(HandlePolicy.NO_OPS, response.inferredResult, 'No processing required');
  },
};

/**
 * Add custom script filter to configuration
 * @param config Unified configuration management object provided by LingmaExtensionSDK
 */
export function modifyConfig(config: Config) {
  config.postContentHandlers.push(llmCompletionResultAuditHandler);
  return config;
}

function getIpAddress() {
  const interfaces = os.networkInterfaces();
  for (const devName in interfaces) {
    const iface = interfaces[devName];

    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (
        alias.family === 'IPv4' &&
        alias.address !== '127.0.0.1' &&
        !alias.internal
      ) return alias.address;
    }
  }

  return 'No IP address found';
}

